package com.msl.debezium.controller;

import com.msl.debezium.common.DateUtil;
import com.msl.debezium.common.Msg;
import com.msl.debezium.common.RedisUtil;
import com.msl.debezium.common.ResultCodeEnum;
import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/cdc/dataSource")
@Api(value = "切换数据源", tags = "DynamicDataSourceController")
@ApiResponses({@ApiResponse(code = 200, message = "OK,请求成功"),@ApiResponse(code = 400, message = "bad-request,客户端请求错误")
              ,@ApiResponse(code = 500, message = "服务器内部错误"),@ApiResponse(code = 403, message = "未授权访问")})
public class DynamicDataSourceController {

    private final Logger logger = LoggerFactory.getLogger(DynamicDataSourceController.class);

    @Autowired
    private RedisUtil redis;

    @GetMapping("/changeDs/{ds}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ds",value="ds",required = true,allowableValues = "VM,WIN",allowMultiple = false),
            @ApiImplicitParam(name = "pwd",value="pwd",required = true,example = "123dbe211124",allowMultiple = false)
    })
    @ApiOperation(value = "changeDs",notes = "改变数据源接口")
    public Msg<Map> changeDs(@PathVariable String ds, @RequestParam String pwd) {
        Msg<Map> msg = Msg.ok();
        try {
            String today = DateUtil.dateDayToStr(new Date(), DateUtil.DATE_DAY_FORMAT);
            String correctPwd = "123debe"+today;
            if(!correctPwd.equals(pwd)){
                Msg.err(ResultCodeEnum.FAIL,"密码错误");
            }
            // 根据参数值的不同，切换数据源
            redis.set("debe_db_datasource",ds);
            logger.info("changeDs finish, debe_db_datasource:"+ds);
            // 清除线程内部变量数据源key
            //DataSourceContextHolder.removeDataSourceType();
            Set podSet = redis.sGet("debe_db_pod");
            Map map = new TreeMap();
            map.put("db",ds);
            map.put("podList",new TreeSet(podSet));
            msg.setData(map);
        }catch (Exception e){
            Msg.err(ResultCodeEnum.SERVER_ERROR,"未知异常，请联系管理员");
        }
        return msg;
    }

}
